<!-- 房屋管理 -->
<template>
  <div>
    <div class="header">
      <div class="title">
        <div style="margin-top: 5px">
      
          <a-space style="margin-left: 10px">
            <span>开始时间：</span>
            <a-date-picker v-model:value="startDate" :format="dateFormat" :disabledDate="disabledFutureDate"  />
          </a-space>
          <a-space style="margin-left: 10px">
            <span>结束时间：</span>
            <a-date-picker v-model:value="endDate" :format="dateFormat" :disabledDate="disabledFutureDate"  />
          </a-space>
          <a-space style=" margin-top: 5px; margin-left: 25px">
            <span>核验来源：</span>
            <a-select ref="select" v-model:value="role_type" style="width: 120px">
              <a-select-option value="4">乡镇</a-select-option>
              <a-select-option value="3">区级</a-select-option>
              <a-select-option value="2">市级</a-select-option>
            </a-select>
          </a-space>
          <a-space style=" margin-top: 5px; margin-left: 15px">
            <span>关键字：</span>
            <a-input
              v-model:value="txtKeyWord"
              placeholder="请输入关键字进行查询"
              style="width: 256px; margin-top: -10px"
            />
          </a-space>
          <a-space class="search-btn">
            <a-button type="primary" @click="searchBtn" style="float: right; margin-right: 10px; margin-top: 5px">查询</a-button>
          </a-space>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <a-space class="search-btn" style="float: right; margin-right: 10px; margin-top: 5px">
            <a-button type="primary" @click="handleMxExport"> 导出明细表</a-button>
          </a-space>
        </div>
      </div>
      <div style="width: 100%; background: #fff; height: 40px">
        <div style="width: 30%; float: left; font-size: 16px; padding-left: 20px; line-height: 37px"
          ><home-outlined two-tone-color="#eb2f96" /><span style="padding: 0px 10px">{{
            title
          }}</span></div
        >
        <div
          style="
            width: 30%;
            float: right;
            font-size: 16px;
            padding-left: 20px;
            line-height: 37px;
            text-align: right;
            padding-right: 20px;
          "
          ><a style="color: blue" @click="getBack"
            ><arrow-left-outlined two-tone-color="#eb2f96" style="padding: 0px 10px" />返回上一页</a
          ></div
        >
      </div>
      <a-table
        :columns="columns"
        :data-source="computedTableData"
        :page-size-options="pageSizeOptions"
        :loading="loading"
        bordered
        :pagination="false"
        size="middle"
        :scroll="{ x: 'calc(700px + 50%)', y: 850 }"
      >
        <!-- <template #action>
          <a>action</a>
        </template> -->
      </a-table>
      <div class="pagination">
        <a-pagination
          show-size-changer
          v-model:current="pageIndex"
          v-model:pageSize="pageSize"
          :total="total"
          @show-size-change="onShowSizeChange"
        />
      </div>

      <!-- <BasicTable @register="registerTable">
          <template #id="{ record }"> </template>
      </BasicTable> -->
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { useRouter, useRoute } from 'vue-router';
  import { HomeOutlined, ArrowLeftOutlined } from '@ant-design/icons-vue';
  import { ref, onMounted, onBeforeMount, computed, watch } from 'vue';
  import { HcHourseList } from '/@/api/demo/api';
  import { getRegion } from '/@/api/demo/system'; //统计工作进展
  import { useGlobSetting } from '/@/hooks/setting';
  import moment from 'moment';
  import dayjs from 'dayjs';
  import { useUserStore } from '/@/store/modules/user';
  import { downloadByUrl } from '/@/utils/file/download';
  import { useCheckStore } from '/@/store/modules/checkStore';
  const userStore = useUserStore();
  const router = useRouter();
  const route = useRoute();
  const globSetting = useGlobSetting();
  const loading = ref<any>(true);
  // 表格的 ref Dom名称
  const checkAll = ref(true);
  const checkValue= ref<string>('0');
  const role_type = ref<string>('');
  const txtKeyWord = ref<string>(''); //核验人员姓名
  const cs = ref<string[]>([]); //层数
  const dateFormat = 'YYYY-MM-DD';
  const startDate = ref<any>(null); // 开始时间
  const endDate = ref<any>(null); // 结束时间
  const strXzqm = ref<string>('');
  const title = ref<string>('');
  let regionList = ref<any[]>([]);
  let pageIndex = ref(1);
  let pageSize = ref(20);
  let total = ref(0);
  let detailTableHeight = ref<number>(600); // 表格高度
  let tableHeight = ref<number>(0); // 表格高度
  const pageSizeOptions = ref<string[]>(['100', '200', '300']);
  let tableSource = ref<any>([]);
  const disabledFutureDate = (current) => {
  return current && current > moment().endOf('day');
};
  // 目标页面读取
  const store = useCheckStore();
  const { startTime, endTime, roletype, txtKey, xzqdm, fooler, category, currentTitle } =
    store.formData || {};
  const baseColumns = [
    { title: '序号', width: 50, dataIndex: 'index', key: 'index', align: 'center', fixed: 'left' },
    {
      title: '乡镇/街道',
      dataIndex: 'towndm',
      key: 'towndm',
      align: 'center',
      width: 170,
    },
    {
      title: '村名称',
      dataIndex: 'villagedm',
      key: 'villagedm',
      align: 'center',
      width: 150,
    },
    {
      title: '户主姓名',
      dataIndex: 'hzxm',
      key: 'hzxm',
      align: 'center',
      width: 150,
    },
    {
      title: '地址',
      dataIndex: 'address',
      key: 'address',
      align: 'center',
      width: 300,
    },
    {
      title: '房屋编号',
      dataIndex: 'fwbh',
      key: 'fwbh',
      align: 'center',
      width: 170,
      customCell: (row, index, column) => {
        let isNoHzyh = row.town !== '汇总' ? true : false;
        let style = 'cursor:pointer;text-decoration: underline; color: blue;';
        let isNoZero = row[column.key] !== 0 ? true : false;
        return {
          style: `${isNoHzyh === true && isNoZero ? style : ''}`,
          class: 'cell-hover',
          onClick: async () => {
            getDetailData(row);
          },
        };
      },
    }
  ];
  const computedTableData = computed(() => {
    console.log(tableSource.value);
    return tableSource.value;
  });
    // 获取当前标题（响应式）
  const columns = computed(() => {
    const cols = [...baseColumns]; // 创建新数组
    if (category != '') {
      if (category == 'hccount' || category == 'ydbcount' || category == 'wdbcount' || category == 'yhcount'  || category == 'zgcount' || category == 'sycount') {
        cols.push({
          title: '核验人员姓名',
          dataIndex: 'nickname',
          key: 'nickname',
          align: 'center',
          width: 150,
        });
        cols.push({
          title: '核验时间',
          dataIndex: 'create_on',
          key: 'create_on',
          align: 'center',
          width: 250,
        });
        cols.push({
          title: '核验来源',
          dataIndex: 'yhly',
          key: 'yhly',
          align: 'center',
          width: 100,
        });
        if (category == 'ydbcount' || category == 'wdbcount') {
          cols.push({
            title: '是否达标',
            dataIndex: 'jsrysstd',
            key: 'jsrysstd',
            align: 'center',
            width: 100,
          });
        }else if (category == 'yhcount' || category == 'zgcount' || category == 'sycount') {
          cols.push({
            title: '隐患项',
            dataIndex: 'check_name',
            key: 'check_name',
            align: 'center',
            width: 100,
          });
          cols.push({
            title: '是否整改',
            dataIndex: 'zg_value',
            key: 'zg_value',
            align: 'center',
            width: 100,
          });
          cols.push({
            title: '是否复核',
            dataIndex: 'jczt',
            key: 'jczt',
            align: 'center',
            width: 100,
          });
        }
      }
      console.log('---------------------------', cols);
    }
    return cols;
  });

  const getCode = async () => {
    if (startTime != null && startTime != '') {
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties
      const sTime = moment(startTime).format('YYYY-MM-DD');
      const eTime = moment(endTime).format('YYYY-MM-DD');
      const start: any = dayjs(sTime);
      const end: any = dayjs(eTime);
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties
      startDate.value = start;
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties
      endDate.value = end;
    }

    // eslint-disable-next-line vue/no-side-effects-in-computed-properties
    role_type.value = roletype ?? '';
    // eslint-disable-next-line vue/no-side-effects-in-computed-properties
    txtKeyWord.value = txtKey ?? '';
    // eslint-disable-next-line vue/no-side-effects-in-computed-properties
    cs.value = fooler ?? null;
    if(fooler!=null && fooler!='')
    {
      checkAll.value=false
    }
    // eslint-disable-next-line vue/no-side-effects-in-computed-properties
  };
  async function getData() {
    console.log('+++++++++++++++++++++++');
    if (startDate.value == null) {
      let currentDate = moment().format('YYYY-MM-DD');
      const start: any = dayjs(currentDate);
      const end: any = dayjs(currentDate);
      startDate.value = start;
      endDate.value = end;
    }

    let params: any = {
      pageindex: pageIndex.value,
      pagesize: pageSize.value,
      startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
      endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
      roletype: role_type.value,
      txtKeyWord: txtKeyWord.value,
      xzqdm: xzqdm ?? '',
      filed: category ?? '',
      cs: cs.value + '',
    };
    console.log('xzq', params);
    if (strXzqm.value != undefined && strXzqm.value != '') {
      params.xzqdm = strXzqm.value[0];
      params.towndm = strXzqm.value[1];
      params.villagedm = strXzqm.value[2];
    }
    console.log('xzq', strXzqm.value);
    let res = await HcHourseList(params);
    let zcount = vtotal(res.items, 'zcount');
    let hccount = vtotal(res.items, 'hccount');
    let hcl = Math.round(parseFloat((hccount / zcount) * 100)).toFixed(2) + '%';
    let 合计_count = '汇总';
    let yhcount = vtotal(res.items, 'yhcount');
    let zgcount = vtotal(res.items, 'zgcount');

    let wzgcount = vtotal(res.items, 'syyhcount');
    let yhccount = vtotal(res.items, 'yhccount');
    let whccount = vtotal(res.items, 'whccount');
    let ydbcount = vtotal(res.items, 'ydbcount');
    let wdbcount = vtotal(res.items, 'wdbcount');
    let dbl = Math.round(parseFloat((ydbcount / hccount) * 100)).toFixed(2) + '%';
    let tallObj = {
      xzq: 合计_count,
      zcount: zcount,
      hccount: hccount,
      hcl: hcl,
      yhcount: yhcount,
      zgcount: zgcount,
      whccount: whccount,
      syyhcount: wzgcount,
      wdbcount: wdbcount,
      ydbcount: ydbcount,
      dbl: dbl,
      yhccount: yhccount,
    };

    let list = res.items;
    tableSource.value = list;
    tableSource.value.push(tallObj);
    total.value = res.total;
    loading.value = false;
    title.value = currentTitle + '(' + res.total + ')';
}
  // 计算总数的方法
  function vtotal(arr: any, item: any) {
    let total = arr.reduce((pre: any, cur: any) => {
      return parseInt(pre) + parseInt(cur[item]);
    }, 0);
    return total;
  }

  const getDetailData = async (row: any) => {
    router.push({
      path: '/utils/houseCheckLog',
      query: {
        xzq: row.xzq,
        town: row.towndm,
        village: row.villagedm,
        hzxm: row.hzxm,
        fwbh: row.fwbh,
        filed: category,
        startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
        endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
        roletype: role_type.value,
        txtKeyWord: txtKeyWord.value,
        xzqdm: xzqdm ?? '',
        cs: cs.value + '',
      },
    });
  };
  function handleMxExport() {
    const uriBase = `${globSetting.apiBaseUrl}${globSetting.apiUrl}`;
    const tk = userStore.getToken;
    let l_xzqdm = '';
    let towndm = '';
    let villagedm = '';
    if (strXzqm.value[0] != undefined) {
      l_xzqdm = strXzqm.value[0];
    }else
    {
      l_xzqdm = xzqdm + '';
    }
    if (strXzqm.value[1] != undefined) {
      towndm = strXzqm.value[1];
    }
    if (strXzqm.value[2] != undefined) {
      villagedm = strXzqm.value[2];
    }
    downloadByUrl({
      url:
        uriBase +
        '/export/hymx/exporthymx?access_token=' +
        tk +
        '&yhly=' +
        role_type.value +
        '&filed=' +
        category +
        '' +
        '&xzqdm=' +
        l_xzqdm +
        '&towndm=' +
        towndm +
        '&villagedm=' +
        villagedm +
        '&startTime=' +
        startDate.value.format('YYYY-MM-DD') +
        '&endTime=' +
        endDate.value.format('YYYY-MM-DD'),
      target: '_blank',
    });
  }
  function getUserInfo() {
    const userStore = useUserStore();
    // userInfo.value = userStore?.getUserInfo;
  }

  function searchBtn() {
    loading.value = true;
    getData();
  }
  // 当"全部"复选框状态变化时
  const onCheckAllChange = (e) => {
    if (e.target.checked) {
      // 如果选中了"全部"，清空其他所有选择
      cs.value = [];
    }
  };
  const handleChange = (checkedValues) => {
    console.log('当前选中的楼层:', checkedValues);
    checkAll.value=false;
    // 处理"全部"选项的特殊逻辑
    if (checkedValues.includes('0')) {
      // 如果选择了"全部"，则只保留"全部"选项
      cs.value = ['0'];
    }
    fetchDataWithCsFilter(cs.value)
  };
  const fetchDataWithCsFilter = (values) => {
    // 构建查询条件
    let condition = '';
    if (!values.includes('0') && values.length > 0) {
      condition = `${values.join(',')}`;
      if (!cs.value.concat(condition)) {
      cs.value.push(condition)}
    }
    
    // 调用API或执行查询
    console.log('查询条件:', condition);
  };
  async function getRegionData() {
    let res: any = await getRegion();
    regionList.value = res;
  }
  const getBack = () => {
   let params = {
      startTime: startTime,
      endTime: endTime,
      roletype: roletype,
      fooler: cs,
      txtKey: txtKeyWord,
    };
    const store = useCheckStore();
    store.setData(params); // 存入Pinia

    router.push({
      path: '/hcManager/VerifyStatisticalDetails',
    });
  };
  function onChange(value) {
    strXzqm.value = value;
  }
  const getTableHeight = () => {
    setTimeout(() => {
      detailTableHeight.value = window.innerHeight - 200;
    });
  };

  const onShowSizeChange = (pageIndex: number, pageSize: number) => {
    getTableHeight();
  };
  watch(pageSize, () => {
    // console.log('pageSize', pageSize.value);
    getData();
  });
  watch(pageIndex, () => {
    // console.log('current', pageIndex.value);
    getData();
  });
  onBeforeMount(() => {
    getUserInfo();
  });
  onMounted(() => {
    getRegionData();
    getCode();
    // getTableHeight();
    getData();
  });
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
  #map {
    height: calc(100vh - 140px);
  }
  .x-houseMng-search {
    z-index: 100;
    margin: 6px;
    position: absolute;
  }
  .root-house-mng-main {
    margin: 6px;
  }
  .x-village-tabs {
    width: 60vw;
    margin-top: 6px;
    margin-left: 40px;
    :deep(.ant-form) {
      margin-top: 6px;
    }
  }
</style>
<style>
  .ant-form-item {
    margin-bottom: 15px !important;
  }
</style>
